package com.example.toolsdemo.tools;

import android.util.Log;

/**
 * ClassName:ByteUtil
 * Package:com.npt.filereceiver
 * Description:
 *
 * @date: 2021/6/15 11:30
 * @author: Wang Wanquan
 * @mail WongWonquanMail@gmail.com
 */
public class ByteUtil {
    private static final String TAG = "ByteUtil";


    /**
     * 10进制byte数组转换为16进制字符串
     *
     * @param input 10进制byte[]
     * @return hexString
     */
    public static String bytesToHexString(byte[] input) {
        if (input.length > 0) {
            StringBuffer sf = new StringBuffer();
            for (byte b :
                    input) {
                int temp = b & 0xff;//防止大于128时,输出负数
                temp |= 0xffffff00;//防止小于16时,输出时丢失第一位的0
                String hex = Integer.toHexString(temp).substring(6).toUpperCase();//获得一个111111[b]的8位hexStriing,截取最后两位
                sf.append(hex);
            }
            return sf.toString();
        } else {
            return "";
        }
    }


    public static int bytesToInt(byte[] input) {
        if (input.length > 0) {
            int count = 0;
            for (int i = input.length; i > 0; i--) {
                byte b = input[input.length - i];
                count += ((b & 0xff) << 8 * (i - 1));
            }
            return count;
        } else {
            Log.d(TAG, "bytesToInt: error");
            return 0;
        }
    }


    /**
     * 直接异或计算字节数组
     *
     * @param text 字节数组
     * @return 异或结果
     */
    public static byte xorByte(byte[] text) {
        byte result = text[0];
        for (int i = 1; i < text.length; i++) {
            result ^= text[i];
        }
        return result;
    }


    /**
     * 计算相邻两位字节的异或值
     *
     * @param hexString hexString16进制字符串
     * @return 一位byte的异或值
     */
    public static byte xorByte(String hexString) {
        byte[] text = hexStringToBytes(hexString);
        byte result = text[0];
        for (int i = 1; i < text.length; i++) {
            result ^= text[i];
        }
        return result;
    }

    public static byte[] hexStringToBytes(String hexString) {
        if (hexString.length() < 0) {
            return new byte[]{0};
        } else {
            if (hexString.length() % 2 == 1) {
                hexString = "0" + hexString;
            }
            byte[] result = new byte[hexString.length() / 2];
            for (int i = 0; i < hexString.length() / 2; i++) {
                String temp = hexString.substring(i * 2, i * 2 + 2);
                int tempInt = Integer.parseInt(temp, 16);
                result[i] = (byte) tempInt;
            }
            return result;
        }
    }
}
